package com.lx.util;

import com.lx.entity.Manager;

import java.io.*;
import java.util.List;

/**
 * @author c先生
 * @date 2022年04月12日 上午 9:03:53
 * @describe    操作管理员的工具类
 */

public class ManagerUtil {

    //登录功能
    public boolean login(String name,String password){
        List<Manager> managerList = this.getAllManagers();
        for (Manager manager : managerList) {
            if(manager.getManagerName().equals(name) &&
               manager.getPassword().equals(password)){
                return true;
            }
        }
        return false;
    }

    //注册功能
    public boolean regManager(List<Manager> manager){
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        try {
            fos = new FileOutputStream("E:/Users/c先生/Desktop/manager.txt");
            oos = new ObjectOutputStream(fos);
            oos.writeObject(manager);
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }finally {
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    //获取所有的用户对象
    public List<Manager> getAllManagers(){
        File file = new File("E:/Users\\c先生/Desktop/manager.txt");;
        ObjectInputStream ois = null;
        List<Manager> listManager = null;
        if(file.exists()){
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(file);
                ois = new ObjectInputStream(fis);
                listManager = (List<Manager>) ois.readObject();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }finally {
                if (ois != null) {
                    try {
                        ois.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return listManager;
        }else {
            String filePath = file.getAbsolutePath();
            String newPath = filePath.substring(0,filePath.lastIndexOf("\\"));//获得文件的绝对路径
            File file1 = new File(newPath);
            if(!file1.exists()){//如果路径不存在就创建路径
                file1.mkdirs();
            }
            try {
                file.createNewFile();//路径存在就直接创建manager.txt文件
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
            return null;
    }
}
